package com.vue.admin.service.common.jwt;

import com.vue.admin.service.common.context.EnvironmentThreadContext;
import com.vue.admin.service.common.util.CommonUtils;
import com.vue.admin.service.module.sys.entity.UserEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;

/**
 * @program: vue-admin-service
 * @description: Shiro 工具类
 * @author: zhangyangyang
 * @create: 2020-04-03 13:26
 **/
public class ShiroUtil {

    /**
     * 获取验证码
     * @param key
     * @return
     */
    public static String getKaptcha(String key) {
        String kaptcha = ShiroUtil.getSessionAttribute(key).toString();
        ShiroUtil.getSession().removeAttribute(key);
        return kaptcha;
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Object getSessionAttribute(Object key) {
        return ShiroUtil.getSession().getAttribute(key);
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获得当前环境中用户对象实例
     *
     * @return
     */
    public static UserEntity getUserEntity() {
        SecurityManager securityManager = ThreadContext.getSecurityManager();
        if (securityManager == null){
            return null;
        }
        UserEntity userEntity = (UserEntity)SecurityUtils.getSubject().getPrincipal();
        if (CommonUtils.isNullOrEmpty(userEntity)){
            userEntity = (UserEntity) EnvironmentThreadContext.get(EnvironmentThreadContext.USER_INFO_CONTEXT);
        }
        return userEntity;
    }

    public static Integer getUserId() {
        return ShiroUtil.getUserEntity().getId();
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static void setSessionAttribute(Object key, Object value) {
        ShiroUtil.getSession().setAttribute(key, value);
    }
}
